package com.muh.rabbitmq;

import com.rabbitmq.client.*;

import java.util.HashMap;
import java.util.Map;

public class FristConsumerGetResponse {
    private static final String HOST_NAME = "39.104.74.101";
    private static final int PORT = 5672;
    private static final String QUEUE_NAME = "test3";//队列名称
    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "admin";
    private static final String VIRTUAL_HOST = "/mirror";//虚拟机

    public static void main(String[] args) throws Exception {
        //建立连接Factory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_NAME);
        factory.setPort(PORT);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setVirtualHost(VIRTUAL_HOST);

        //建立连接
        Connection connection = factory.newConnection();
        //创建一个通道用来传输数据
        Channel channel = connection.createChannel();

        /**
         * 申明一个对列，队列名，durable是否持久化，exclusive是否独占，autodelete是否自动删除消息
         * 这几个参数跟创建对列的页面是一致的
         * 如果broker上没有对列，那么就会自动创捷对列
         * 但是如果broker上已经有了这个对列，那么对列的属性必须匹配，否则会报错
         */
        Map<String, Object> params = new HashMap<String, Object>();
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        channel.basicQos(100);//每个worker同时处理100个消息
        //pull拉模式
        GetResponse getResponse = channel.basicGet(QUEUE_NAME, false);
        byte[] body = getResponse.getBody();
        Envelope envelope = getResponse.getEnvelope();
        int messageCount = getResponse.getMessageCount();
        AMQP.BasicProperties props = getResponse.getProps();

        System.out.println("------------------------------------");
        String routingKey = envelope.getRoutingKey();
        System.out.println("routingKey: " + routingKey);
        String contentType = props.getContentType();
        System.out.println("contentType: " + contentType);
        long deliveryTag = envelope.getDeliveryTag();
        System.out.println("deliveryTag: " + deliveryTag);
        System.out.println("messageCount: " + messageCount);
        System.out.println("content:"+new String(body, "UTF-8"));
        channel.basicAck(deliveryTag, false);
        System.out.println("------------------------------------");
        channel.close();
        connection.close();
    }
}
